package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.mapper.ApUnlikesBehaviorMapper;
import com.heima.behavior.service.IApUnlikesBehaviorService;
import org.springframework.stereotype.Service;
import com.heima.behavior.dto.BehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.mapper.ApUnlikesBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApUnlikesBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.Threadlocals.UserThreadLocalUtil;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP不喜欢行为表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-08-04
 */
@Service
public class ApUnlikesBehaviorServiceImpl extends ServiceImpl<ApUnlikesBehaviorMapper, ApUnlikesBehavior> implements IApUnlikesBehaviorService {

    @Autowired
    IApBehaviorEntryService apBehaviorEntryService;

    /**
     * 根据文章ID和设备ID查询是否喜欢
     * @param articleId
     * @param entryId
     * @return
     */
    @Override
    public ApUnlikesBehavior findByArticleIdAndEntryId(Integer articleId, Integer entryId) {

        LambdaQueryWrapper<ApUnlikesBehavior> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApUnlikesBehavior::getEntryId, entryId);
        wrapper.eq(ApUnlikesBehavior::getArticleId, articleId);
        ApUnlikesBehavior one = this.getOne(wrapper);
        return one;
    }

    @Override
    public ResponseResult unlike(BehaviorDto dto){
            User user = UserThreadLocalUtil.get();
            ApBehaviorEntry entry = apBehaviorEntryService.getEntry(user.getUserId(), dto.getEquipmentId());

            //根据文章id查表
            LambdaQueryWrapper<ApUnlikesBehavior> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUnlikesBehavior::getArticleId, dto.getArticleId());
            ApUnlikesBehavior one = this.getOne(queryWrapper);


        ApUnlikesBehavior unlikesBehavior = new ApUnlikesBehavior();
        unlikesBehavior.setEntryId(entry.getId());
        unlikesBehavior.setArticleId(dto.getArticleId());
        unlikesBehavior.setOperation(dto.getOperation());
        unlikesBehavior.setCreatedTime(new Date());
        //如果没有新增,存在则保存
        if(one==null){
            this.save(unlikesBehavior);
        } else{
            unlikesBehavior.setId(one.getId());
            this.updateById(unlikesBehavior);
        }
        return ResponseResult.okResult();

    }
}
